package toOffer;

/**
 * @author YuanAo
 * @date 2024/7/1 13:42
 * @description 训练计划V
 */

/**
 * 题目
 */
public class LCR171 {
    public static void main(String[] args) {
        int intersectVal = 8;
        int[] listA = {4, 1, 8, 4, 5};
        int[] listB = {5, 0, 1, 8, 4, 5};
        int skipA = 2;
        int skipB = 3;

        ListNode head4 = new ListNode(listA[4]);
        ListNode head3 = new ListNode(listA[3]);
        head3.next = head4;
        ListNode head2 = new ListNode(listA[2]);
        head2.next = head3;
        ListNode head1 = new ListNode(listA[1]);
        head1.next = head2;
        ListNode headA = new ListNode(listA[0]);
        headA.next = head1;

        ListNode head5B = new ListNode(listB[5]);
        ListNode head4B = new ListNode(listB[4]);
        head4B.next = head5B;
        ListNode head3B = new ListNode(listB[3]);
        head3B.next = head4B;
        ListNode head2B = new ListNode(listB[2]);
        head2B.next = head3B;
        ListNode head1B = new ListNode(listB[1]);
        head1B.next = head2B;
        ListNode headB = new ListNode(listB[0]);
        headB.next = head1B;

        ListNode node = getIntersectionNode(headA, headB);
//        ListNode node = turnOverLinkedList(headA);
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
    }

    /**
     *
     * @param headA
     * @param headB
     * @return
     */
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode nodeA = turnOverLinkedList(headA);
        ListNode nodeB = turnOverLinkedList(headB);
        ListNode tn = nodeA;
        ListNode n = null;
        int count = 0;
        while (tn.next != null){
            if (nodeA.val == nodeB.val){
                n = tn;
                tn = tn.next;
                count++;
            }
        }
        ListNode rl = nodeA;
        // 反转后的上一个节点就是未反转前的下一个节点
        while (count > 0){
            nodeA = nodeA.next;
            count--;
        }
        nodeA.next = null;
        return turnOverLinkedList(rl);
    }

    /**
     * 反转链表
     *
     * @param node
     * @return
     */
    public static ListNode turnOverLinkedList(ListNode node) {

        ListNode tempNode;
        ListNode tn = null;
        while (node != null) {
            tempNode = node.next;
            node.next = tn;
            tn = node;
            node = tempNode;
        }
        return tn;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
